﻿using AiBLSmartEdu.Module.SmartStockSense.API.Configurations;
using AiBLSmartEdu.Module.SmartStockSense.API.DTOs;
using FrameworkCore.DI;
using FrameworkCore.Helpers;
using Microsoft.Extensions.Options;

namespace AiBLSmartEdu.Module.SmartStockSense.API;

#nullable disable

public class StockLicenceProvider : ISingletonDependency
{
    private readonly IOptions<SmartStockSenseSettings> _optSmartStockSenseSettings;
    private List<StockLicence> _stockLicences;

    public StockLicenceProvider(IOptions<SmartStockSenseSettings> optSmartStockSenseSettings)
    {
        _optSmartStockSenseSettings = optSmartStockSenseSettings;
        GenerateLicence();
    }

    public (string licence,bool disable) GetLicence()
    {
        ResetNonTodayExpiredLicences();

        var licence = _stockLicences.FirstOrDefault(x => !x.Disable)?.Key;
        var disable = string.IsNullOrWhiteSpace(licence);

        return (licence, disable);
    }

    public void DisableLicence(string licence)
    {
        var stockLicence = _stockLicences.FirstOrDefault(item => item.Key == licence);
        if (stockLicence != null)
        {
            stockLicence.Disable = true;
            stockLicence.DisableDate = DateTime.Now.Date;
        }
    }

    public void ResetNonTodayExpiredLicences()
    {
        var disableLicences = _stockLicences.Where(x => x.Disable && x.DisableDate.Value.Day != DateTime.Now.Day).ToList();
        if (disableLicences.Count > 0)
        {
            foreach (var disableLicence in disableLicences)
            {
                disableLicence.Disable = false; // 重新启用许可证
                disableLicence.DisableDate = null; // 清除禁用日期
            }
        }
    }

    private void GenerateLicence()
    {
        _stockLicences = _optSmartStockSenseSettings.Value.Licences.Select(licence => new StockLicence
        {
            Key = licence,
            Disable = false
        }).ToList();
    }
}